#ifndef _PARSER_H_
#define _PARSER_H_

#include <iostream>
#include <stdlib.h>

using namespace std;

#include "lookaheadlexer.h"
#include "token.h"
#include "error.h"

class Parser {
protected:
    Lexer *input;
    Token **lookahead;
    int k;
    int p = 0;
public:
    Parser(Lexer *input, int k) {
        this->input = input;
        this->k = k;
        lookahead = new Token*[k];
        for (int i = 1; i <= k; i++)
            consume();
    }

    void consume() {
        lookahead[p] = input->next_token();
        p = (p + 1) % k;
    }

    Token *LT(int i) {
        return lookahead[(p + i - 1) % k];
    }

    int LA(int i) {
        return LT(i)->type;
    }

    void match(int x) {
        if (LA(1) == x) {
            cout << LT(1)->to_string() << endl;
            consume();
        }
        else {
            string s = "expecting ";
            s += input->get_token_name(x);
            s += "; found ";
            s += LT(1)->text;
            throw Error(s);
        }
    }
};

#endif
